package com.kehutong.house.app;

import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;
import com.kehutong.house.entity.DeviceManagement;
import com.kehutong.house.entity.DoorPassRecord;
import com.kehutong.house.entity.HeartBeatRecord;
import com.kehutong.house.entity.SupplierConfig;
import com.kehutong.house.util.DateUtils;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.util.UUIDGenerator;

import java.sql.Timestamp;

/**
 * TODO
 *
 * @author zhouweipeng
 * @version 1.0
 * @date 2021/7/24 10:47
 */
@MvcAction
@ReqMapping("/kht-bin/basic/door")
public class DoorAction {
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    private Logger log= LoggerFactory.getLogger(DoorAction.class);
    /**
     * 设备心跳回调
     * 上报格式{"clockid":123,"devsn":"000123456","hbinterval":30}
     * @param jsonObject
     */
    @ReqMapping("/heartBeatNotify")
    public void heartBeatNotify(JSONObject jsonObject){
        try {
            log.info("伊时利设备心跳回调json==="+jsonObject.toJSONString());
            String clockid=jsonObject.getString("clockid"); //设备编号/机号
            String devsn=jsonObject.getString("devsn");  //设备序列号
            int hbinterval=jsonObject.getInteger("hbinterval");  //心跳间隔时间
            String areaid=jsonObject.getString("areaid");
            ThreadLocalCache.current().setCorpId(areaid);
            HeartBeatRecord heartBeatRecord=new HeartBeatRecord(UUIDGenerator.randomUUID());
            heartBeatRecord.setClockId(clockid);
            heartBeatRecord.setDevsn(devsn);
            heartBeatRecord.setHbinterval(hbinterval);
            DeviceManagement deviceManagement=jdbcSession.findOne(DeviceManagement.class).eq("deviceSeq",devsn)
                    .eq("deviceNo",clockid).exe();
            deviceManagement.setHbinterval(hbinterval);
            deviceManagement.setHeartBeatTime(new Timestamp(System.currentTimeMillis()));
            jdbcSession.updateById(deviceManagement);
            jdbcSession.insert(heartBeatRecord);
        } catch (Exception e) {
            log.error("伊时利设备心跳回调处理出现异常"+e.getMessage(),e);
        }

    }

    /**
     * 通行记录
     * {"rectype":2,"doorseq":"000123456","readerno":"1","passtime":"20210710122315","cardseq":"3415474126","eventremark":"正常卡开门","inout":1,"personid":"123"}
     * @param jsonObject
     */
    @ReqMapping("/passRecordNotify")
    public void passRecordNotify(JSONObject jsonObject){
        try {
            log.info("伊时利通行记录回调json==="+jsonObject.toJSONString());
            String doorSeq=jsonObject.getString("doorseq"); //设备序列号
            String readerNo=jsonObject.getString("readerno"); //设备序列号
            String passTime=jsonObject.getString("passtime"); //设备序列号
            String cardSeq=jsonObject.getString("cardseq"); //设备序列号
            String eventreMark=jsonObject.getString("eventremark"); //设备序列号
            String inOut=jsonObject.getString("inout"); //设备序列号
            String personId=jsonObject.getString("personid"); //用户id
            String areaid=jsonObject.getString("areaid");
            DoorPassRecord doorPassRecord=new DoorPassRecord(UUIDGenerator.randomUUID());
            doorPassRecord.setDoorSeq(doorSeq);
            doorPassRecord.setReaderNo(readerNo);
            doorPassRecord.setCardSeq(cardSeq);
            doorPassRecord.setEventreMark(eventreMark);
            doorPassRecord.setInOut(inOut);
            doorPassRecord.setPersonId(personId);
            Timestamp date= DateUtils.strFormatTimetamp(passTime,DateUtils.PATTERN_2);
            doorPassRecord.setPassTime(date);
            ThreadLocalCache.current().setCorpId(areaid);
            jdbcSession.insert(doorPassRecord);
        } catch (Exception e) {
            log.error("伊时利通行记录回调处理出现异常"+e.getMessage(),e);
        }
    }

    /**
     * 用户所拥有开门权限的门禁
     * @param jsonObject
     * @return
     */
    @ReqMapping("/listDoor")
    public Object listDoor(JSONObject jsonObject){
        return null;
    }
    /**
     * 通行授权二维码
     * @param jsonObject
     * @duetime 到期时间
     * @personId 用户id
     * @deviceId 设备id
     * {
     * "duetime":"20210725111111",
     * "personId":"11",
     * "deviceId":"111"
     * }
     * @return
     */
    @ReqMapping("/authQrCode")
    public Object authQrCode(JSONObject jsonObject){
        try{
            String deviceId=jsonObject.getString("deviceId");
            String personId=jsonObject.getString("personId");
            String dueTime=jsonObject.getString("dueTime");
            //查询设备
            DeviceManagement device=jdbcSession.findById(DeviceManagement.class,deviceId);
            SupplierConfig supplierConfig=jdbcSession.findOne(SupplierConfig.class).eq("supplierId",device.getSupplierId()).exe();
            String method="codeRights";
            String url=supplierConfig.getServiceUrl()+method;
            JSONObject result = doveClient.post(url, http->{
                JSONObject body = new JSONObject();
                body.put("areaId", device.getCommunityId());
                body.put("personId", personId);
                body.put("doorSeq", device.getDeviceSeq());
                body.put("dueTime",dueTime);
                body.put("ext",supplierConfig.getExt());
                http.setBody(body.toString());
            });
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(0, "系统异常！");
        }

    }

    /**
     * 远程开门
     * @param jsonObject
     * @optype 1、开门，2、关门
     * @personId 用户id
     * @deviceId 设备id
     * @dlaytime 开门时长
     * {
     * "opType":"1",
     * "personId":"11",
     * "deviceId":"111",
     * "dlayTime":"10"
     * }
     * @return
     */
    @ReqMapping("/remoteOpenDoor")
    public Object remoteOpenDoor(JSONObject jsonObject){
        try{
            String opType=jsonObject.getString("opType");
            String deviceId=jsonObject.getString("deviceId");
            String personId=jsonObject.getString("personId");
            String dlayTime=jsonObject.getString("dlayTime");
            //查询设备
            DeviceManagement device=jdbcSession.findById(DeviceManagement.class,deviceId);
            SupplierConfig supplierConfig=jdbcSession.findOne(SupplierConfig.class).eq("supplierId",device.getSupplierId()).exe();
            String method="openDoor";
            String url=supplierConfig.getServiceUrl()+method;
            JSONObject result = doveClient.post(url, http->{
                JSONObject body = new JSONObject();
                body.put("opType", opType);
                body.put("areaId", device.getCommunityId());
                body.put("personId", personId);
                body.put("doorSeq", device.getDeviceSeq());
                body.put("dlayTime",dlayTime);
                body.put("ext",supplierConfig.getExt());
                http.setBody(body.toString());
            });
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(0, "系统异常！");
        }

    }

}
